package com.cyys.modules.system.service.org;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyys.common.ql.AR;
import com.cyys.common.ql.AjaxJson;
import com.cyys.common.services.CyysBaseService;
import com.cyys.modules.system.dao.org.OrgNoticeDao;
import com.cyys.modules.system.model.org.OrgNotice;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service("orgNoticeService")
@Transactional(readOnly = true)
public class OrgNoticeService extends CyysBaseService<OrgNoticeDao, OrgNotice> {

	/**
	 * 查询已读明细
	 * @param page
	 * @param orgId
	 * @param noticeId
	 * @return
	 * @throws Exception
	 */
	public IPage userReadDetail(Page page, String orgId, String noticeId, String userName) throws Exception{
		List<Map> list= dao.userReadDetail(page, orgId, noticeId, userName);
		return page.setRecords(list);

	}

	/**
	 * 查看通知公告
	 * @param id 通知ID
	 * @param userId 查看人ID
	 * @return
	 * @throws Exception
	 */
	@Transactional(readOnly = false)
	public AR getNotificationById(String id, String userId) throws Exception {
		AjaxJson ajaxJson=new AjaxJson();
		OrgNotice notice = dao.selectById(id);
		if(notice==null){
			return AR.failed("没有该通知");
		}
		List<Map> readList = getReadList(id, userId);
		if(readList.size()==0){ //未读时
			//保存进用户已读通知表
			dao.insertRead(notice.getOrgId(), id, userId);

			//计算已读未读人数
			notice.setUserRead(notice.getUserRead()+1); //已读人数
			dao.updateById(notice);
		}
		return AR.ok(notice);
	}

	public List<Map> getReadList(String noticeId, String userId) throws Exception{
		return dao.getReadList(noticeId, userId);
	}
}
